package offer.offer02;

import java.util.Stack;

/**
 *
 */
public class S27二叉树的镜像New {
    /**
     * 100, 有点怀疑子树转着转着会不会不是镜像, 不过好像是。
     * 半年后再遇到……
     */
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null) return null;
        mirrorTreeHelp(root);
        return root;
    }
    public void mirrorTreeHelp(TreeNode root){
        if(root == null) return;
        TreeNode temp1;
        temp1 = root.left;
        root.left = root.right;
        root.right = temp1;
        mirrorTreeHelp(root.left);
        mirrorTreeHelp(root.right);
    }

    // 递归, 这个好啊, 这个妙啊……
    public TreeNode mirrorTree2(TreeNode root) {
        if(root == null) return null;
        TreeNode tmp = root.left;
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(tmp);
        return root;
    }

    // 辅助栈, 就add, pop, 栈这个类还是好用
    public TreeNode mirrorTree3(TreeNode root) {
        if(root == null) return null;
        Stack<TreeNode> stack = new Stack<>() {{ add(root); }};
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if(node.left != null) stack.add(node.left);
            if(node.right != null) stack.add(node.right);
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return root;
    }


}
